//
//  HomeViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/3/28.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
class HomeViewController: BaseViewController {

    
    
    let homeItemCell = "homeItemCell"
    
    var homeCellArray:[String]?
    
    @IBOutlet var topViewHeight: NSLayoutConstraint!

    @IBOutlet var headerImageviewHeight: NSLayoutConstraint!
    
    @IBOutlet var headerImageviewWidth: NSLayoutConstraint!
    @IBOutlet var homeCollectionview: UICollectionView!
    
    @IBOutlet var storeNameLabel: UILabel!
    @IBOutlet var userHeaderView: UIImageView!
    @IBOutlet var todayOrderNumLabel: UILabel!
    @IBOutlet var waitPayNumLabel: UILabel!
    
    @IBOutlet var servicingNumLabel: UILabel!
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
         homeCellArray = ["到店服务","客户预约","掌控安装","订单管理","加油管理","优惠券"] 
        requstHomedata()
        requstCheckAppVersion()
        configView()
        
        
    }
    
    func configView() -> Void {
        if kScreenHeight == 480.0 {
            topViewHeight.constant = ScaleHeight(have: false, 270)
        }
        headerImageviewHeight.constant = ScaleHeight(have: false, 79)
        headerImageviewWidth.constant = ScaleHeight(have: false, 79)

        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 1
        homeCollectionview.frame = .zero
        homeCollectionview.collectionViewLayout = layout
        homeCollectionview.delegate = self
        homeCollectionview.dataSource = self
        homeCollectionview.register(UINib(nibName: "HomeCollectionViewCell", bundle: nil),forCellWithReuseIdentifier: homeItemCell)
        homeCollectionview.showsVerticalScrollIndicator = false
    }
    
    func updatehomeVC(homedatamodel:HomeDataModel) -> Void {
        self.storeNameLabel.text = homedatamodel.name
        self.todayOrderNumLabel.text = homedatamodel.total
        self.waitPayNumLabel.text = homedatamodel.money
        self.servicingNumLabel.text = homedatamodel.xiu
        self.userHeaderView.sd_setImage(with: (NSURL(string:(homedatamodel.image))! as URL), placeholderImage: UIImage.init(named: "defultHeaderImg"))
        self.userHeaderView.roundCorner(radius: self.userHeaderView.frame.height/2)
    }
    
    @IBAction func leftBtnPress(_ sender: UIButton) {
        let signinWorkVC = SigninWorkViewController()
        signinWorkVC.title = "打卡"; self.navigationController?.pushViewController(signinWorkVC, animated: true)
    }
    
    @IBAction func rightBtnPress(_ sender: UIButton) {
        let settingVC = SettingViewController()
        settingVC.title = "设置"; self.navigationController?.pushViewController(settingVC, animated: true)
    }
    //网络请求
    //首页数据
    func requstHomedata() -> Void {
        
        Alamofire.request(homeDataUrl, method:.post, parameters: ["storeid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    var basemodel = BaseResponseOfModel<HomeDataModel>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        print("数据成功")
                        self.updatehomeVC(homedatamodel: basemodel.data!)
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //检查版本做自动更新
    func requstCheckAppVersion() -> Void {
        
        Alamofire.request(merchantCheckAppVersionUrl, method:.post, parameters:nil)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    var basemodel = CheckAppVersionModel()
                    basemodel = CheckAppVersionModel.deserialize(from: response.value)!
                    
                    
                    //主程序当前版本号
                    let infoDictionary = Bundle.main.infoDictionary!
                    let majorVersion = infoDictionary["CFBundleShortVersionString"]
                    let currentVersion = majorVersion as! String
                    //线上版本号
                    let onlineVersion = basemodel.response?.version
                    
                    if onlineVersion?.compare(currentVersion) == ComparisonResult.orderedDescending {
//                        print("线上版本更高")
                        
                        let alertController = UIAlertController(title: "温馨提示",
                                                                message:"亲，目前AppStore有最新版本哦，点击确定可以去更新啦", preferredStyle: .alert)
                        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                        let okAction = UIAlertAction(title: "确定", style: .default, handler: {
                            action in
                            UIApplication.shared.openURL(NSURL.init(string: "itms-apps://itunes.apple.com/cn/app/id1382604502?mt=8")! as URL)
                        })
                        alertController.addAction(cancelAction)
                        alertController.addAction(okAction)
                        self.present(alertController, animated: true, completion: nil)
                        
                    }else {
//                        print("一样，不用升级")
                    }
                    
                    
                    
                    
                    
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


//MARK:delegate
extension HomeViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return (homeCellArray?.count)!
    }
    
  
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: homeItemCell, for: indexPath) as!HomeCollectionViewCell
        let model = homeCellArray![indexPath.item]
        cell.cellLabel.text = model
        cell.cellImageView.image = UIImage.init(named: model)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
         let model = homeCellArray![indexPath.item]
        switch model {
            case "到店服务":
                let arriveStoreVC = ArriveserviceListViewController()
                arriveStoreVC.title = model; self.navigationController?.pushViewController(arriveStoreVC, animated: true)
            case "客户预约":
                let appointmentVC = AppointmentViewController()
                appointmentVC.title = model; self.navigationController?.pushViewController(appointmentVC, animated: true)
            case "员工管理":
                let employeeVC = EmployeeManagerViewController()
                employeeVC.title = model; self.navigationController?.pushViewController(employeeVC, animated: true)
            case "掌控安装":
                let smartControlVC = SmartControlInstallViewController()
                smartControlVC.title = model; self.navigationController?.pushViewController(smartControlVC, animated: true)
            case "服务管理":
                let sotreConfigureVC = StoreConfigureViewController()
                    sotreConfigureVC.title = model; self.navigationController?.pushViewController(sotreConfigureVC, animated: true)
            case "订单管理":
                let orderVC = OrderManagerViewController()
                orderVC.title = model; self.navigationController?.pushViewController(orderVC, animated: true)
            case "加油管理":
                let oilStationVC = OilStationViewController()
                oilStationVC.title = model; self.navigationController?.pushViewController(oilStationVC, animated: true)
            case "优惠券":
                let couponVC = CouponViewController()
                    couponVC.title = model; self.navigationController?.pushViewController(couponVC, animated: true)
            case "店铺管理":
                let storeDetailsVC = StoreDetailsViewController()
                    storeDetailsVC.title = model; self.navigationController?.pushViewController(storeDetailsVC, animated: true)
            case "员工考勤":
                let checkworkVC = CheckWorkViewController()
                checkworkVC.title = model; self.navigationController?.pushViewController(checkworkVC, animated: true)
            case "活动管理":
                let activityVC = ActivityViewController()
                activityVC.title = model; self.navigationController?.pushViewController(activityVC, animated: true)
           case "修车淘价":
            let servicePlatformVC = PlatformTabBarController()
            servicePlatformVC.title = model;
            self.navigationController?.pushViewController(servicePlatformVC, animated: true)
        default:
            break
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let w = (kScreenWidth - 4) / 3
        let h: CGFloat = 115.0
        return CGSize(width: w, height: h)
    }
    
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
//        return CGSize(width: kScreenWidth - 20, height: 10)
//    }
    
    
    
}


